package com.xb.cloud.usercenter.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.xb.cloud.common.constant.DbConstants;
import com.xb.cloud.common.model.OrderStatus;
import com.xb.cloud.gateway.client.ReturnCodes;
import com.xb.cloud.gateway.client.ReturnUtils;
import com.xb.cloud.gateway.client.RtnInfo;
import com.xb.cloud.order.service.client.ProductStockService;
import com.xb.cloud.order.service.client.SellOrderMerchantService;
import com.xb.cloud.order.service.client.SellOrderService;
import com.xb.cloud.order.service.client.bo.SellOrderBo;
import com.xb.cloud.order.service.client.bo.SellOrderItemBo;
import com.xb.cloud.product.merchant.service.client.bo.ShopSkuBo;
import com.xb.cloud.product.service.client.SkuService;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;
import com.xb.cloud.user.service.client.CheckoutInputBo;
import com.xb.cloud.user.service.client.ShoppingCartItemInputBo;
import com.xb.cloud.user.service.client.bo.ProductSkuStockBo;
import com.xb.cloud.usercenter.service.OrderByMerchantApiService;

@Service
public class OrderByMerchantServiceImpl implements OrderByMerchantApiService {

	@Resource
	SkuService skuService;

	@Resource
	ProductStockService productStockService;

	@Resource
	SellOrderMerchantService sellOrderMerchantService;

	/*
	 * 对下单商品进行验证
	 */
	@Override
	public RtnInfo generateOrder(CheckoutInputBo checkoutInputBo) {
		List<ShoppingCartItemInputBo> cartItems = checkoutInputBo.getCartItems();
		List<Long> skuIdList = new ArrayList<>();
		for (ShoppingCartItemInputBo checkoutItem : cartItems) {
			skuIdList.add(checkoutItem.getSkuId());
		}
		List<ShopSkuBo> skuList = skuService.getShopSkuListBySkuIds(skuIdList);

		// 验证库存
		RtnInfo checkSkusCanSaleRtn = checkSkusCanSale(cartItems, skuList);
		if (ReturnUtils.isError(checkSkusCanSaleRtn)) {
			return checkSkusCanSaleRtn;
		}

		SellOrderBo sellOrderBo = buildSellOrder(checkoutInputBo, skuList);

		ServiceReturnInfo returnInfo = sellOrderMerchantService.generateOrder(sellOrderBo);
		if (ServiceReturnUtils.isError(returnInfo)) {
			 return ReturnUtils.error(ReturnCodes.MERCHANT_CREATE_ORDER_ERROR);
		}

		sellOrderBo = (SellOrderBo) returnInfo.getData();
		return ReturnUtils.success(sellOrderBo);
	}

	private SellOrderBo buildSellOrder(CheckoutInputBo checkoutInputBo, List<ShopSkuBo> skuList) {
		Long companyId = checkoutInputBo.getCompanyId();
		Long merchantId = checkoutInputBo.getMerchantId();
		String phone = checkoutInputBo.getPhone();

		List<SellOrderItemBo> itemList = new ArrayList<SellOrderItemBo>();

		Map<Long, ShopSkuBo> skuMap = new HashMap<>();
		for (ShopSkuBo shopSkuBo : skuList) {
			skuMap.put(shopSkuBo.getSkuId(), shopSkuBo);
		}

		Long shopId = null;
		BigDecimal totalSkuAmount = BigDecimal.valueOf(0);
		List<ShoppingCartItemInputBo> cartItems = checkoutInputBo.getCartItems();
		for (ShoppingCartItemInputBo cartItem : cartItems) {
			Long skuId = cartItem.getSkuId();
			ShopSkuBo shopSkuBo = skuMap.get(skuId);

			shopId = shopSkuBo.getShopId();
			BigDecimal priceSale = shopSkuBo.getPriceSale();// 商品价格
			int num = cartItem.getNum();// 商品下单数量
			BigDecimal skuAmount = priceSale.multiply(BigDecimal.valueOf(num));// sku总价
			totalSkuAmount = totalSkuAmount.add(skuAmount);

			SellOrderItemBo orderItem = new SellOrderItemBo();
			orderItem.setCompanyId(companyId);
			orderItem.setMerchantId(merchantId);
			orderItem.setShopId(shopId);
			orderItem.setSkuId(skuId);

			// sku info
			orderItem.setSkuNameCn(shopSkuBo.getSkuNameCn());
			orderItem.setSkuPrice(priceSale);
			orderItem.setSkuNum(num);
			orderItem.setSkuAmount(skuAmount);

			// product info
			orderItem.setProductId(shopSkuBo.getProductId());
			orderItem.setProductPicUrl(shopSkuBo.getDefaultPicURL());
			orderItem.setFrozenRealStockNum(num);// 实际冻结库存=商品下单数量(在sql中更新)

			orderItem.setIsLeaf(DbConstants.TRUE);// 暂时没有组合品
			itemList.add(orderItem);
		}

		SellOrderBo sellOrderBo = new SellOrderBo();
		sellOrderBo.setCompanyId(companyId);
		sellOrderBo.setMerchantId(merchantId);
		sellOrderBo.setShopId(shopId);
		sellOrderBo.setItems(itemList);
		sellOrderBo.setSoStatus(OrderStatus.PENDING_PAYMENT.getCode());// 未支付
		sellOrderBo.setIsLeaf(DbConstants.TRUE);
		sellOrderBo.setSkuAmount(totalSkuAmount);
		sellOrderBo.setOrderAmount(totalSkuAmount);// 一期没有运费等
		sellOrderBo.setGoodReceiverName(checkoutInputBo.getUsername());
		sellOrderBo.setGoodReceiverPhone(phone);
		sellOrderBo.setGoodReceiverAddress(checkoutInputBo.getAddress());
		sellOrderBo.setSoUserRemark(checkoutInputBo.getRemark());
		sellOrderBo.setBusinessType(DbConstants.ORDER_BUS_TYPE_MERCH);

		return sellOrderBo;
	}

	private RtnInfo checkSkusCanSale(List<ShoppingCartItemInputBo> checkoutItemList, List<ShopSkuBo> shopSkuList) {
		List<ShopSkuBo> unavailableSkus = new ArrayList<>();
		List<ShopSkuBo> outStockSkus = new ArrayList<>();

		Map<Long, ShopSkuBo> shopSkuMap = new HashMap<>();
		for (ShopSkuBo shopSkuBo : shopSkuList) {
			shopSkuMap.put(shopSkuBo.getSkuId(), shopSkuBo);
		}

		for (ShoppingCartItemInputBo checkoutItem : checkoutItemList) {
			ShopSkuBo shopSkuBo = shopSkuMap.get(checkoutItem.getSkuId());
			Byte isCanSale = shopSkuBo.getIsCanSale();
			if (!DbConstants.isTrue(isCanSale)) {
				unavailableSkus.add(shopSkuBo);
				continue;
			}

			boolean stockEnough = checkSkuStock(shopSkuBo.getShopId(), shopSkuBo.getProductId(), checkoutItem.getNum());
			if (!stockEnough) {
				outStockSkus.add(shopSkuBo);
				continue;
			}

		}

		Map<String, List<ShopSkuBo>> skuMap = new HashMap<>();
		skuMap.put("unavailableSkus", unavailableSkus);
		skuMap.put("outStockSkus", outStockSkus);

		if (!CollectionUtils.isEmpty(unavailableSkus)) {
			return ReturnUtils.error(skuMap, ReturnCodes.SKU_CANNOT_SALE);
		}
		if (!CollectionUtils.isEmpty(outStockSkus)) {
			return ReturnUtils.error(skuMap, ReturnCodes.SKU_STOCK_NOT_ENOUGH);
		}

		return ReturnUtils.success();
	}

	/**
	 * 验证sku库存， 由shopId+productId确定sku
	 * 
	 * @Title checkSkuStock
	 * @param shopId
	 * @param productId
	 * @param num
	 * @return
	 */
	private boolean checkSkuStock(Long shopId, Long productId, int num) {
		ServiceReturnInfo serviceReturnInfo = productStockService.getProductStockByProductShopWarehouse(productId,
				shopId, DbConstants.DEFAULT_WAREHOUSE_ID);
		if (ServiceReturnUtils.isSuccess(serviceReturnInfo)) {
			if (serviceReturnInfo.getData() == null) {
				return false;
			}

			ProductSkuStockBo skuStockBo = (ProductSkuStockBo) serviceReturnInfo.getData();
			if (!DbConstants.isTrue(skuStockBo.getIsEnabled())) {
				return false;
			}

			Long realFrozenStockNum = skuStockBo.getRealFrozenStockNum();// 实际冻结库存
			Long realStockNum = skuStockBo.getRealStockNum();// 实际库存
			// 可用库存 = 实际库存 - 实际冻结库存
			Long availableStock = realStockNum - realFrozenStockNum;
			if (availableStock.intValue() < num) {
				return false;
			}
		}

		return true;
	}
}
